import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/kan_list_entity.dart';
import 'package:wanxiang_app/bean/record_list_entity.dart';
import 'package:wanxiang_app/bean/simple_entity.dart';
import 'package:wanxiang_app/pages/home/detail.dart';
import 'package:wanxiang_app/widgets/money_textField.dart';
import '../../utils/common.dart';
import '../../utils/constant.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../utils/user_util.dart';
import '../../widgets/account_textField2.dart';
import '../../widgets/myappbar.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';
import '../../widgets/simple_dialog.dart';

class PriceController extends GetxController{
  String title = '';
  @override
  void onInit() {
    super.onInit();
    title = Get.arguments;
    _getKan();
  }
  @override
  void onClose() {
    super.onClose();
    BotToast.closeAllLoading();
  }
  int clickIndex = 0;
  List<Map> tabs=[{'name':'全部','value':''},{'name':'待处理','value':'1'},{'name':'已还价','value':'2'},{'name':'已同意','value':'3'}
    ,{'name':'买家同意','value':'5'},{'name':'已取消','value':'6'}];
  List<KanListData> list = [];
  void _getKan(){
    DioManager.getInstance().post(ServiceUrl.kanList,{
     "user_name": UserUtil.getUSER()?.userName,
      'istatus':tabs[clickIndex]['value']
    }, (data) async {
      KanListEntity bannerEntity = KanListEntity.fromJson(jsonDecode(data));
      list = bannerEntity.data;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _cancel(id){

    showDialog(context: mContext, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){

          DioManager.getInstance().post(ServiceUrl.cancelKan,{
            "user_name": UserUtil.getUSER()?.userName,
            'bargaining_id':id.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getKan();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
          Navigator.pop(context1);
        }
      },
        msg: "是否确认取消砍价？",
        cancelText: '取消',
        sureText: "确认",
      );
    });

  }

  late BuildContext mContext ;
  void _reject(id){
    showDialog(context: mContext, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          DioManager.getInstance().post(ServiceUrl.sellReject,{
            "user_name": UserUtil.getUSER()?.userName,
            'bargaining_id':id.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getKan();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
          Navigator.pop(context1);
        }
      },
        msg: "是否拒绝本次报价，拒绝后该次交易失败",
        cancelText: '取消',
        sureText: "拒绝",
      );
    });
  }

  String backPrice = '';
  void _backPrice(id){
    DioManager.getInstance().post(ServiceUrl.backPrice,{
      "user_name": UserUtil.getUSER()?.userName,
      'bargaining_id':id.toString(),
      'sell_price':backPrice
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      _getKan();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _agree(id){

    showDialog(context: mContext, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){


          DioManager.getInstance().post(ServiceUrl.sellAgree,{
            "user_name": UserUtil.getUSER()?.userName,
            'bargaining_id':id.toString(),
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getKan();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
          Navigator.pop(context1);
        }
      },
        msg: "是同意本次报价，同意后请及时配合客服完成后续操作？",
        cancelText: '取消',
        sureText: "同意",
      );
    });

  }
  EasyRefreshController easyRefreshController = EasyRefreshController(
    controlFinishRefresh: false,
    controlFinishLoad: true,
  );

}

class PriceBuyerPage extends   GetView<PriceController>  {

late PriceController controller ;
late BuildContext context ;
@override
Widget build(BuildContext context1) {
  Get.lazyPut<PriceController>(() => PriceController());
  controller = Get.find();
  context = context1;
  controller.mContext = context1;
  return GetBuilder<PriceController>(
    builder: (_){
      return  Scaffold(
          appBar: MyAppBar(context: context, title: controller.title,hasLeading: true,),
          backgroundColor: Colors.white,
          body:_content());
    },
  );

}


List<Widget> tabsItems(){
  List<Widget> aa = [];
  for(int i =0 ;i<controller.tabs.length;i++){
    aa.add(_tabItem(controller.tabs[i]['name'],i));
  }
  return aa;
}

Widget _tabItem(name,index){
  return InkWell(
    onTap: (){
      controller.clickIndex = index;
      controller._getKan();
      controller.update();
    },
    child: Container(
      margin: EdgeInsets.only(right: 10.w),
      child: Column(
        children: [
          Text(name,style: TextStyle(color:Color(0xFF333333),fontSize: 14.sp),),
          SizedBox(height: 10.h,),
          controller.clickIndex == index?
          Container(
            width: 27.w,
            height: 2.h,
            color: Color(0xFF007BE5),
          ):Container( height: 2.h,)
        ],
      )
    )
  ) ;
}

Widget _content(){
  return
      Container(
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 10.h),
              padding: EdgeInsets.only(left: 10.w,right: 10.w),
              child:
              SingleChildScrollView(
                scrollDirection:Axis.horizontal,
                child: Row(
                  children: tabsItems(),
                ),
              )

            )
            ,
            controller.list.length==0?Container():Container(height: 8.h,color: Color(0xFFF7F8FC),),
            controller.list.length==0?_empty():
            Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height - 8.h - 120.h,
              child: _refresh(),
            )
          ],
        )
      )
;
}

  Widget _refresh(){
    return   Scaffold(
        backgroundColor: Colors.white,
        body:  EasyRefresh(
          header: ClassicHeader(
            dragText: 'Pull to refresh'.tr,
            armedText: 'Release ready'.tr,
            readyText: 'Refreshing...'.tr,
            processingText: 'Refreshing...'.tr,
            processedText: 'Succeeded'.tr,
            noMoreText: 'No more'.tr,
            failedText: 'Failed'.tr,
            messageText: 'Last updated at %T'.tr,
          ),
          footer: ClassicFooter(
            dragText: 'Pull to load'.tr,
            armedText: 'Release ready'.tr,
            readyText: 'Loading...'.tr,
            processingText: 'Loading...'.tr,
            processedText: 'Succeeded'.tr,
            noMoreText: 'No more'.tr,
            failedText: 'Failed'.tr,
            messageText: 'Last updated at %T'.tr,
          ),
          controller: controller.easyRefreshController,
          onRefresh: () async {
            controller._getKan();
          },
          onLoad: () async {
            controller.easyRefreshController.finishLoad(
                IndicatorResult.noMore );
          },
          child: ListView.separated(
            itemBuilder: (context, index) {
              return _gameItems(controller.list[index]);
            }, separatorBuilder: (BuildContext context, int index) {
            return Container(height: 8.h,color: Color(0xFFF7F8FC),);
          }, itemCount: controller.list.length,
          ),
        ));
  }

Widget _empty(){
  return Container(
    margin: EdgeInsets.only(top: 50.h),
    alignment: Alignment.center,
    child: Image.asset(Constant.IMG_BASE+'empty.png',width: 150.w,height: 127.h,),
  );
}

  Widget _gameItems(KanListData item){
    return
      InkWell(
          onTap: (){
            Get.to(()=>DetailPage(),arguments: {
              "title":item.title,
              "record_id":item.channelId.toString(),
              "channel_name":'',
              "goods_id":item.goodsId.toString(),
            },preventDuplicates:false);
          },
          child: Container(
            margin: EdgeInsets.only(left: 16.w,right: 13.w,top: 12.h),
            child:
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('订单号：${item.id}',style: TextStyle(
                        color: Color(0xFF333333),
                        fontWeight: FontWeight.bold,
                        fontSize: 12.sp
                    ),),

                    Text(Common.kanbuyerStatusToText(item.isIstatus),style: TextStyle(
                        color: Color(0xFF007BE5),
                        fontSize: 12.sp
                    ),),
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 10.h,bottom: 10.h),
                  height: 1.h,
                  color: Color(0xFFF3F3F3),
                ),
                Row(
                  children: [
                    Container(
                        width: 100.w,
                        height: 78.h,
                        child: Stack(
                          children: [
                            _officer(),
                            ClipRRect(
                                borderRadius: BorderRadius.circular(10.r),
                              child: Image.network(Common.realPicPath(item.imgUrl,),width: 100.w,height: 78.h,fit: BoxFit.cover,)
                            )
                          ],
                        )

                    ),
                    SizedBox(width: 14.w,),
                    Container(
                        width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w,
                        child:  Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(item.title,
                              style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,),maxLines: 1,    textAlign: TextAlign.left,
                              overflow: TextOverflow.ellipsis,),
                            SizedBox(height: 10.h,),
                            Text('区服：${item.categoryText}',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
                            SizedBox(height: 6.h,),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                item.isMsg==1?
                                _second():Container(),
                              ],
                            ),

                          ],
                        )
                    )
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Row(
                      children: [
                        Text('原价：',style: TextStyle(color: Color(0xFF999999),fontSize: 12.sp),),
                        Text('¥',style: TextStyle(color: Color(0xFF999999),fontSize: 12.sp),),
                        Text(item.oldPrice,style: TextStyle(color: Color(0xFF666666),fontSize: 18.sp),),
                      ],
                    ),


                    SizedBox(width: 10.w,),
                    Row(
                      children: [
                        Text('报价：',style: TextStyle(color: Color(0xFF999999),fontSize: 12.sp),),
                        Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                        Text(item.newPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 18.sp),),
                      ],
                    ),
                    SizedBox(width: 10.w,),
                 Row(
                   children: [
                     Text('还价：',style: TextStyle(color: Color(0xFF999999),fontSize: 12.sp),),
                     Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                     Text(item.offerPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 18.sp),),
                   ],
                 )

                  ],
                ),
                SizedBox(height: 13.h,),
                // _info(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text( Common.transferDate(item.bargainingTime),style: TextStyle(color: Color(0xFF999999),fontSize: 12.sp),),
                    _btns(item.isIstatus,item)
                  ],
                ),
                SizedBox(height: 10.h,),

              ],
            )
            ,
          )
      )
    ;
  }

  Widget _second(){
    return Container(
      width: 55.w,
      height: 24.h,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4.r),
          border: Border.all(width: 1.w,color: Color(0xFF4EBCFF))
      ),
      child: Text('可二次',style: TextStyle(
          color: Color(0xFF4EBCFF),
          fontSize: 12.sp
      ),),
    );
  }

  Widget _officer() {
    return Container(
      child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
    );
  }

  Widget _info(){
    return Container(
      color: Color(0xFFFBFBFB),
      padding: EdgeInsets.all(10.w),
      child: Column(
        children: [
          Row(
            children: [
              Flexible(
                  flex:1,
                  child:   Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text('状态:',style: TextStyle(
                              color: Color(0xFF666666),
                              fontSize: 13.sp
                          ),),
                          Text('在售',style: TextStyle(
                              color: Color(0xFFFF9100),
                              fontSize: 13.sp
                          ),)
                        ],
                      ),


                    ],
                  )),
              Flexible(
                flex: 1,
                child:  Text('上架：2023.05.10  10:30',style: TextStyle(
                    color: Color(0xFF666666),
                    fontSize: 13.sp
                ),),
              ),
            ],
          ),
          SizedBox(height: 7.h,),
          Row(
            children: [
              Expanded(
                flex: 1,
                child:  Text('商品类型:官方',style: TextStyle(
                    color: Color(0xFF666666),
                    fontSize: 13.sp
                ),),
              ),

              Expanded(
                flex: 1,
                child:  Text('营地号:asasasasa',style: TextStyle(
                    color: Color(0xFF666666),
                    fontSize: 13.sp
                ),),
              ),
            ],
          ),
          SizedBox(height: 7.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('商品编号：111111111111111111111111',style: TextStyle(
                  color: Color(0xFF666666),
                  fontSize: 13.sp
              ),),

            ],
          ),
        ],
      ),
    );
  }

  Widget _btns(status,KanListData item){
  // if(status == 0){
  //   return _btnWait(item);
  // }
  // if(status == 1){
  //   return _btnIng();
  // }
  if(status == 1 || status == 8){
    return _btnIng2(item);
  }
  // if(status == 3){
  //   return _btnPay();
  // }

    return Container();
  }

  Widget _btnWait(KanListData item){
    return Row(
      children: [
        InkWell(
          onTap: (){
            controller._cancel(item.id.toString());
          },
          child: Container(
              padding: EdgeInsets.fromLTRB(16.w, 5.h, 16.w, 5.h),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color:  Colors.white,
                border: Border.all(color: Color(0xFFC7C7C7),width: 1),
                borderRadius: BorderRadius.all(Radius.circular(20.r)),
              ),
              child: Text(
                '取消',style: TextStyle(
                  fontSize: 12.sp,
                  color: Color(0xFFC7C7C7)
              ),
              )
          )
        )
  ,
        // SizedBox(width: 5.w,),
        // Container(
        //     padding: EdgeInsets.fromLTRB(16.w, 5.h, 16.w, 5.h),
        //     alignment: Alignment.center,
        //     decoration: BoxDecoration(
        //       color:  Colors.white,
        //       border: Border.all(color: Color(0xFFC7C7C7),width: 1),
        //       borderRadius: BorderRadius.all(Radius.circular(20.r)),
        //     ),
        //     child: Text(
        //       '立即支付',style: TextStyle(
        //         fontSize: 12.sp,
        //         color: Color(0xFFC7C7C7)
        //     ),
        //     )
        // ),
      ],
    );
  }

Widget _btnIng(){
  return Row(
    children: [
      Container(
          padding: EdgeInsets.fromLTRB(16.w, 5.h, 16.w, 5.h),
          margin: EdgeInsets.only(top: 26.h,bottom: 20.h),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(20.r)),
            border: Border.all(color:Color(0xFFC7C7C7),width: 1)
          ),
          child: Text(
            '取消砍价',style: TextStyle(
              fontSize: 12.sp,
              color: Color(0xFFC7C7C7)
          ),
          )
      ),

    ],
  );
}

Widget _btnIng2(KanListData item){
  return Row(
    children: [
      InkWell(
        onTap: (){
          controller._reject(item.id);
        },
        child: Container(
            padding: EdgeInsets.fromLTRB(16.w, 5.h, 16.w, 5.h),
            margin: EdgeInsets.only(right: 5.w),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border.all(color: Color(0xFFC7C7C7),width: 1),
              borderRadius: BorderRadius.all(Radius.circular(20.r)),
            ),
            child: Text(
              '拒绝',style: TextStyle(
                fontSize: 13.sp,
                color: Color(0xFFC7C7C7)
            ),
            )
        )
      )
  ,
      item.isIstatus==8?Container():
    InkWell(
      onTap: (){
        _showSingle(item.id.toString());
      },
      child:    Container(
          padding: EdgeInsets.fromLTRB(16.w, 5.h, 16.w, 5.h),
          margin: EdgeInsets.only(right: 5.w),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            border: Border.all(color: Color(0xFFC7C7C7),width: 1),
            borderRadius: BorderRadius.all(Radius.circular(20.r)),
          ),
          child: Text(
            '还价',style: TextStyle(
              fontSize: 13.sp,
              color: Color(0xFFC7C7C7)
          ),
          )
      )
    )
   ,
    InkWell(
      onTap: (){
        controller._agree(item.id.toString());
      },
      child:     Container(
          padding: EdgeInsets.fromLTRB(16.w, 5.h, 16.w, 5.h),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            border: Border.all(color: Color(0xFFC7C7C7),width: 1),
            borderRadius: BorderRadius.all(Radius.circular(20.r)),
          ),
          child: Text(
            '同意',style: TextStyle(
              fontSize: 13.sp,
              color: Color(0xFFC7C7C7)
          ),
          )
      )
    )
  ,
    ],
  );
}

Future<Future<int?>> _showSingle(id) async {
  return showModalBottomSheet<int>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context1) {
        return AnimatedPadding(
            padding: MediaQuery.of(context1).viewInsets, // 我们可以根据这个获取需要的padding
            duration: const Duration(milliseconds: 100),
            child:  Container(
                height: 200.h,
                clipBehavior: Clip.antiAlias,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20.0),
                    topRight: Radius.circular(20.0),
                  ),
                ),
                child: Column(
                  children: [
                    SizedBox(height: 15.h,),
                    Text('还价',style: TextStyle(
                        fontSize: 15.sp
                    ),),
                    Container(
                        margin: EdgeInsets.all(10.w),
                        decoration: BoxDecoration(
                            border: Border.all(color: Color(0xFFE4E4E4),width: 1.w)
                        ),
                        child:
                        MoneyTextField(key: const ValueKey('title'), contentStrCallBack: (value){
                          controller.backPrice = value;
                        })

                    ),
                    Container(
                      margin: EdgeInsets.only(left: 20.w),
                      alignment: Alignment.centerLeft,
                      child:  Text('输入还价金额后，耐心等待买家的回复哦',
                        textAlign: TextAlign.left,
                        style: TextStyle(
                            fontSize: 12.sp,
                            color: Color(0xFF666666)
                        ),)
                    )
                    ,
                    InkWell(
                        onTap: (){
                          controller._backPrice(id);
                          Navigator.pop(context1);
                        },
                        child:  Container(
                          height: 40.h,
                          margin: EdgeInsets.all(10.w),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8.r),
                              color: Color(0xFF007BE5)
                          ),
                          child: Text('确定',style: TextStyle(
                              color: Colors.white,
                              fontSize: 13.sp
                          ),),
                        )
                    )

                  ],
                )
            )
        ) ;
      });
}

Widget _btnPay(){
  return Row(
    children: [
      Container(
          height: 36.h,
          margin: EdgeInsets.only(top: 26.h,bottom: 20.h),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color:  Color(0xFFC7C7C7),
            borderRadius: BorderRadius.all(Radius.circular(20.r)),
          ),
          child: Text(
            '立即支付',style: TextStyle(
              fontSize: 13.sp,
              color: Color(0xFFC7C7C7)
          ),
          )
      ),

    ],
  );
}

}